package com.xmb.wechat.view.alipay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.blankj.utilcode.util.ToastUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.AliPayBillBean;
import com.xmb.wechat.delegate.AliPayBillDetailDelegate;
import com.xmb.wechat.util.MoneyFormat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.OnClick;

/**
 * @Author lijiangop
 * @CreateTime 2020/5/25 16:07
 */
public class AliPayBillDetailActivity extends BaseActivity {

    private AliPayBillDetailDelegate mDelegate;

    public AliPayBillDetailActivity() {
        super(R.layout.activity_alipay_bill_detail);
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, AliPayBillDetailActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void initView() {
        mDelegate = new AliPayBillDetailDelegate(this);
        List<AliPayBillBean> datas = WechatStartApplication.getBoxStore().boxFor(AliPayBillBean.class).query().build().find();
        if (datas.size() > 0)
            sortData(datas);
    }

    @SuppressLint("SimpleDateFormat")
    private void sortData(List<AliPayBillBean> data) {
        //最终的数据合集
        ArrayList<AliPayBillBean> result = new ArrayList<>();
        //记录时间数据在集合中的角标
        ArrayList<Integer> positions = new ArrayList<>();
        //记录收支情况
        ArrayList<String> expends = new ArrayList<>();
        ArrayList<String> incomes = new ArrayList<>();
        //排序
        Collections.sort(data);
        //分组
        double expend = 0;//支出
        double inCome = 0;//收入
        AliPayBillBean pre = null;
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy年M月");
        SimpleDateFormat onlyMonthFormat = new SimpleDateFormat("M月");
        for (AliPayBillBean entity : data) {
            if (!isInSameMonth(monthFormat, pre, entity)) {//不是同一月
                //新建一个时间数据
                AliPayBillBean aliPayBillBean = new AliPayBillBean(777);
                aliPayBillBean.setMonthInYear(getYearAndMonth(monthFormat, onlyMonthFormat, entity.getTradeTime()));
                result.add(aliPayBillBean);
                //记录新增的时间数据的角标
                positions.add(result.size() - 1);
                //添加上月的收支汇总（第一条时间数据不添加)
                if (pre != null) {
                    expends.add("支出 ¥ " + formatNumber(expend));
                    incomes.add("收入 ¥ " + formatNumber(inCome));
                }
                //清空上月的收支汇总
                expend = 0;
                inCome = 0;
            }
            //支出、收入汇总
            if (entity.isExpend())
                expend += getMoney(entity.getMoney());
            else
                inCome += getMoney(entity.getMoney());
            //添加交易数据
            result.add(entity);
            pre = entity;
        }
        //添加上月的收支汇总（最后一条数据）
        expends.add("支出 ¥" + formatNumber(expend));
        incomes.add("收入 ¥" + formatNumber(inCome));
        //设置收支情况
        for (int i = 0; i < positions.size(); i++) {
            Integer position = positions.get(i);
            if (result.size() > position && expends.size() > i) {
                AliPayBillBean aliPayBillBean = result.get(position);
                aliPayBillBean.setExpend(expends.get(i));
                aliPayBillBean.setIncome(incomes.get(i));
            }
        }
        mDelegate.addData(result);
    }

    /**
     * String转Double
     *
     * @param money
     * @return
     */
    private double getMoney(String money) {
        if (TextUtils.isEmpty(money))
            return 0;
        try {
            return Double.parseDouble(money);
        } catch (Exception e) {
            ToastUtils.showShort("金额输入有误");
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取年月
     *
     * @param monthFormat
     * @param onlyMonthFormat
     * @param time
     * @return
     */
    private String getYearAndMonth(SimpleDateFormat monthFormat, SimpleDateFormat onlyMonthFormat, long time) {
        Calendar todayCalendar = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        if (todayCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {//当年
            if (todayCalendar.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)) //当月
                return "本月";
            else
                return onlyMonthFormat.format(new Date(time));
        } else
            return monthFormat.format(new Date(time));
    }

    /**
     * 按显示要求格式化数字
     *
     * @param arg
     * @return
     */
    private String formatNumber(double arg) {
        String s = MoneyFormat.formatMoney(arg);
        if (s.length() > 6)
            return new StringBuffer(s).insert(s.length() - 6, ",").toString();
        return s;
    }

    /**
     * 比较两个时间是否一样(年月)
     *
     * @param monthFormat
     * @param pre
     * @param aliPayBillBean
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    private boolean isInSameMonth(SimpleDateFormat monthFormat, AliPayBillBean pre, AliPayBillBean aliPayBillBean) {
        if (pre == null)
            return false;
        return TextUtils.equals(monthFormat.format(new Date(pre.getTradeTime())), monthFormat.format(new Date(aliPayBillBean.getTradeTime())));
    }

    @OnClick(R2.id.iv_back)
    public void onViewClicked() {
        finish();
    }

}
